package com.jiadakeji.ppm.api.v1;

import com.jiadakeji.ppm.api.common.JsonResult;
import com.jiadakeji.ppm.common.coderule.CodeRuleFeeReceive;
import com.jiadakeji.ppm.common.coderule.GetCode;
import com.jiadakeji.ppm.common.coderule.GetCodeByRule;
import com.jiadakeji.ppm.common.utils.DecimalUtils;
import com.jiadakeji.ppm.common.utils.StringUtils;
import com.jiadakeji.ppm.common.utils.WechatUtils;
import com.jiadakeji.ppm.common.utils.XmlUtils;
import com.jiadakeji.ppm.common.web.BaseController;
import com.jiadakeji.ppm.modules.business.dao.CustomerDao;
import com.jiadakeji.ppm.modules.business.dao.FeeChargeDao;
import com.jiadakeji.ppm.modules.business.dao.FeeReceiveDao;
import com.jiadakeji.ppm.modules.business.entity.Customer;
import com.jiadakeji.ppm.modules.business.entity.FeeCharge;
import com.jiadakeji.ppm.modules.business.entity.FeeReceive;
import com.jiadakeji.ppm.modules.business.service.FeeReceiveService;
import com.jiadakeji.ppm.modules.weixin.entity.WechatUnifiedorderNotifyRequest;
import com.jiadakeji.ppm.modules.weixin.entity.WechatUnifiedorderNotifyResponse;
import com.jiadakeji.ppm.modules.weixin.entity.WechatUnifiedorderRetrun;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;

@RestController("v1_feeReceiveController")
@RequestMapping(value = "${apiPath}/v1/feeReceive")
public class FeeReceiveController  extends BaseController {

    @Autowired
    private FeeReceiveService feeReceiveService;
    @Autowired
    private FeeReceiveDao feeReceiveDao;
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private FeeChargeDao feeChargeDao;


    @RequestMapping("/payFeeChargeWechat")
    public JsonResult<WechatUnifiedorderRetrun> payFeeChargeWechat(@RequestBody FeeReceive feeReceive, HttpServletRequest request){
        JsonResult<WechatUnifiedorderRetrun> result = new JsonResult<>();
        if(StringUtils.isBlank(feeReceive.getCustomerId())) {
            return result.setCodeAndMessage(-1, "customerId 不能为空");
        }
        if(StringUtils.isBlank(feeReceive.getFeeChargeId())){
            return result.setCodeAndMessage(-1,"feeChargeId 不能为空");
        }

        Customer customer = customerDao.get(feeReceive.getCustomerId());
        if(null == customer){
            return result.setCodeAndMessage(-1,"用户不存在");
        }
       FeeCharge feeCharge =  feeChargeDao.get(feeReceive.getFeeChargeId());
        if(null == feeCharge){
            return result.setCodeAndMessage(-1,"找不到当前应收费用");
        }
        if(feeCharge.getStatus().equals(FeeCharge.STATUS_FINISH)){
            return result.setCodeAndMessage(-1, "费用已经收过");
        }
        FeeReceive fr = new FeeReceive();
        fr.setFeeChargeId(feeReceive.getFeeChargeId());
        fr.setTotalFee(feeCharge.getTotalFee());
        fr.setFeebackMoney(feeCharge.getFeebackMoney());
        fr.setCustomerId(customer.getId());
        fr.setType(FeeReceive.TYPE_WECHAT);
        fr.setPayAmount(DecimalUtils.add(fr.getTotalFee(),fr.getFeebackMoney()));

        GetCode getCode = new GetCodeByRule(new CodeRuleFeeReceive());
        fr.setCode(getCode.generateCode());
        fr.setCashier("1");
        result = feeReceiveService.payByWechat(fr,customer,request);
        return result;
    }


    @ResponseBody
    @RequestMapping("/wechatNotify")
    public void wechatNotify(HttpServletRequest request, HttpServletResponse response){

        logger.info("微信回调开始");
        //1. 获取到微信回调传回的信息
        try {

            String requestXml = WechatUtils.readInfoFromHttpRequest(request);//收到微信发送的信息

            WechatUnifiedorderNotifyResponse wechatResponse = new WechatUnifiedorderNotifyResponse();

            if(requestXml == null || requestXml.isEmpty()){
                wechatResponse.setReturn_code("FAIL");
                logger.error("回调参数为null或空");
                response.getWriter().write(XmlUtils.jacksonObjToXml(wechatResponse));
                return ;
            }

            //1.xml转换为对象
            WechatUnifiedorderNotifyRequest wechatrequest = (WechatUnifiedorderNotifyRequest) XmlUtils.xmlToObject(WechatUnifiedorderNotifyRequest.class,requestXml);

            //2.判断通知是否正常，又异常返回
            if(wechatrequest.getReturn_code().equals("FAIL")){
                wechatResponse.setReturn_code("FAIL");
                logger.error("回调异常");
                response.getWriter().write(XmlUtils.jacksonObjToXml(wechatResponse));
                return ;
            }

            //3.验证签名
            String sign = WechatUtils.checkNotifySign(requestXml,response);

            if(!wechatrequest.getSign().equals(sign)){
                wechatResponse.setReturn_code("FAIL");
                wechatResponse.setReturn_msg("验证不通过sign错误");
                response.getWriter().write(XmlUtils.jacksonObjToXml(wechatResponse));
                return ;
            }

            FeeReceive feeReceive =  feeReceiveDao.getByCode(wechatrequest.getOut_trade_no());
            if(feeReceive == null){
                wechatResponse.setReturn_code("FAIL");
                wechatResponse.setReturn_msg("没有此订单");
                response.getWriter().write(XmlUtils.jacksonObjToXml(wechatResponse));
                return ;
            }
            Double totalPrice = 0.0;
            if(feeReceive != null){
                totalPrice = feeReceive.getPayAmount()*1000/10;
            }
            //四舍五入
            BigDecimal bg = new BigDecimal(totalPrice).setScale(2, BigDecimal.ROUND_HALF_UP);
            Double payPrice = bg.doubleValue();

            if(!payPrice.equals(Double.valueOf(wechatrequest.getTotal_fee()))){
                wechatResponse.setReturn_code("FAIL");
                wechatResponse.setReturn_msg("金额不匹配");
                response.getWriter().write(XmlUtils.jacksonObjToXml(wechatResponse));
                return ;
            }

            System.out.println("-------order.status为--"+feeReceive.getStatus()+"-----");
            // 4.处理订单
            if(feeReceive != null && feeReceive.getStatus().equals(FeeReceive.STATUS_WAIT_PAY)){
                feeReceive.setStatus(FeeReceive.STATUS_PAY_SUCCESS);//付款成功
                FeeCharge feeCharge = feeChargeDao.get(feeReceive.getFeeChargeId());
                feeCharge.setStatus(FeeCharge.STATUS_FINISH);
                int stat = feeReceiveDao.updateOptimisticLock(feeReceive);
                if(stat==1){
                    feeChargeDao.update(feeCharge);
                    wechatResponse.setReturn_code("SUCCESS");
                    wechatResponse.setReturn_msg("OK");
                    response.getWriter().write(XmlUtils.jacksonObjToXml(wechatResponse));
                    return ;
                }
            }

            wechatResponse.setReturn_code("SUCCESS");
            wechatResponse.setReturn_msg("OK");
            response.getWriter().write(XmlUtils.jacksonObjToXml(wechatResponse));
            return ;

        }catch (Exception e){
            e.printStackTrace();
            logger.error("微信回调异常："+e.getMessage());
        }

    }




}
